home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1995 July / macformat-026.iso / mac / Shareware City / Developers / video-toolbox-95-01-14-c / VideoToolbox / VideoToolboxSources / SetEntriesQuickly.c < prev    next >
Encoding:
Text File  |  1995-01-13  |  45.2 KB  |  1,163 lines  |  [TEXT/MPCC]

  1. /*
  2. SetEntriesQuickly.c
  3.  
  4. SetEntriesQuickly loads your video card’s clut as quickly as possible.
  5.  
  6. SetEntriesQuickly was written by many people, and the “final” result has not
  7. been tested on all the computers and video devices it’s meant to support. The
  8. best test is simply to run TimeVideo, which gives it a thorough workout on all
  9. of your computer’s video devices. Please send the report “TimeVideo results” to
  10. denis_pelli@isr.syr.edu, and I’ll add your test results to “Video bugs” and the
  11. following list.
  12.  
  13. VIDEO DEVICES CERTIFIED by TimeVideo as compatible with SetEntriesQuickly():
  14. 1. Ok:
  15. “Macintosh Display Card 8•24 GC” (.Display_Video_Apple_MDCGC)
  16. Quadra 900 “Macintosh C Built-In Video” (only tested in 1,2,4,8-bit modes)
  17. Quadra 950 “Macintosh G Built-In Video” (only tested in 1,2,4,8,16-bit modes)
  18.  
  19. 2. Ok when loading whole clut at once, but fail read-back test when loading one 
  20. entry at a time (at least on the Quadra 840av). Bug reported by Ken Alexander 
  21. <U12940@UICVM.BITNET> and Wei Xie. This problem does not occur on most Macs.
  22. Apple 8•24 "Macintosh Display Card" (.Display_Video_Apple_MDC version 272)
  23.  
  24. 3. Ok, except for visible hash (dynamic black specks) during clut loading:
  25. Apple “Mac II High-Resolution Video Card” (.Display_Video_Apple_HRVC)
  26. Apple “Toby frame buffer card” (.Display_Video_Apple_TFB version 5)
  27. Mac IIci “Macintosh II Built-In Video” (.Display_Video_Apple_RBV1)
  28.  
  29. 4. Don't work (hopefully will be fixed soon):
  30. RasterOps “ProColor 32” (.RasterOps 1.0 32XL Video Driver version 9327)
  31.  
  32. CONTRIBUTORS TO THIS LIST
  33. Ken Alexander <U12940@UICVM.BITNET> (bug in SetEntriesQuickly)
  34. Kyle Cave, cavekr@ctrvax.vanderbilt.edu (Quadra 700)
  35. Wei Xie (bug in SetEntriesQuickly for Apple 8•24 in Quadra 840AV)
  36.  
  37. Some Macintosh video drivers are poorly written; they take too long (more than a
  38. frame time) to load the clut. This is makes it impossible to do clut animation
  39. for temporal modulation etc., for which one needs to be able to reload the clut
  40. on each frame. At one time, many of us thought that the limitation was in
  41. hardware, in the RAMDAC, but we were wrong. Raynald Comptois disassembled
  42. several video drivers and wrote his own programs to load the clut quickly, and
  43. his programs manage to do it within a frame. Raynald was kind enough to share
  44. his code with me. I passed it on to Peter Lennie and Bill Haake, who polished
  45. it, making it compatible with the 68040 processor, and added support for more
  46. cards. I polished their work, made the routines self contained, adding a
  47. “device” argument to allow use in Macs that have more than one video device, and
  48. quickly figuring out all the key parameters (mode, pixelSize, DAC size, and clut
  49. size). There are now two alternative front ends: SetEntriesQuickly() for new
  50. users, and macltset() for backward compatibility with programs that used
  51. Raynald’s original routines. This modularity has increased run time only
  52. slightly, a fraction of a millisecond.
  53.  
  54. New drivers are hard to write, since they must directly address the registers of
  55. the video card, which are unique to each video card and undocumented. So the
  56. author of a driver must disassemble the original video driver and figure things
  57. out on his or her own. A lot of work.
  58.  
  59. SetEntriesQuickly is unlike the standard video drivers in the following ways:
  60. 1. SetEntriesQuickly always takes less than 2 ms to load the whole clut. 
  61. Some video drivers, e.g. for Apple’s 8•24 card, take several frames (>30 ms) to 
  62. finish loading the clut.
  63. 2A. SetEntriesQuickly does not wait for VBL, so a visible glitch may appear on
  64. the current frame, at least on some older video cards (e.g. Hi-Res, Toby, and
  65. Mac IIci). (You can prevent this glitch by calling SetEntriesQuickly only at
  66. blanking time. Use a VBL task or WaitForBlanking().) Newer cards and computers
  67. seem to have dual ported video clut memory so you can write at any point in the
  68. frame cycle without noticeable glitch, though of course you may want to synch
  69. the update for other reasons.
  70. 2B. A flag argument “waitForNextBlanking” is provided, but at present this
  71. option is only supported for the Toby video card.
  72. 3. SetEntriesQuickly ignores the gamma table, yielding the same result as using
  73. the standard video driver with an uncorrected gamma table. E.g. after calling
  74. GDUncorrectedGamma(device).
  75. 4. SetEntriesQuickly() does nothing and returns an error if the arguments
  76. specify loading of an out-of-range index. 
  77. 5. SetEntriesQuickly() does nothing and returns an error if the “count”
  78. specifies zero entries. This is contrary to the (bizarre) Apple convention that
  79. a setEntries control call with a count corresponding to zero entries will result
  80. in loading of entries specified by the “value” field of the ColorSpec.
  81. 6. SetEntriesQuickly does not have immediate access to the video driver’s
  82. private tables. Therefore the first time you call SetEntriesQuickly() for a 
  83. particular device there is an extra delay of about 1 ms while some key
  84. information is ferreted out. That information is cached, so subsequent calls
  85. for the same device will be fast, spending most of their time loading the clut.
  86.  
  87. Two front ends are provided, for compatibility with two distinct traditions:
  88.  
  89. OSErr SetEntriesQuickly(GDHandle device,short start,short count,ColorSpec *table);
  90.  
  91. SetEntriesQuickly() uses the same calling convention as the VideoToolbox routine
  92. GDSetEntries() and, except for adding the GDHandle argument to specify the
  93. device, is also the same as Apple’s SetEntries() Color Manager routine,
  94. documented in Inside Macintosh V-143. Apple specifies special behavior when
  95. count==-1, but we don’t support that here and simply return with an error. I
  96. suggest that new users use SetEntriesQuickly rather that macltset. “start” is
  97. the index of the first clut entry to load, and should be greater than or equal
  98. to zero. “count” is the number of entries to load, minus 1. (Yes, “minus 1”,
  99. that’s Apple’s confusing convention.) “table” is a Colorspec array. (Each ColorSpec
  100. element is a structure consisting of a two-byte “value”, which is not used, and
  101. a 6-byte “rgb”, which, in turn is a structure of three 16-bit unsigned short
  102. ints: red, green, and blue. Apple’s convention is that the MOST SIGNIFICANT BITS
  103. of the 16-bit color values are used. It’s good practice in your programs to
  104. provide full 16-bit values, so that when you upgrade to fancier video cards with
  105. more-than-eight bit DACs your programs will benefit from the extra precision
  106. without needing any change. Returns zero if successful, nonzero if unsuccessful,
  107. i.e. illegal arguments.
  108.  
  109. short macltset(GDHandle device,short start
  110.     ,unsigned short* red,unsigned short* green,unsigned short* blue,short count1);
  111.  
  112. macltset() uses a calling convention established by Raynald Comtois, and
  113. provides backward compatibility with older programs. “red”, “green”, and “blue”
  114. are arrays of 16-bit unsigned short ints, of which the LEAST SIGNIFICANT BITS
  115. are used. “start” is the index of the first entry to change. “count1” is the
  116. number of entries to change (contrary to Apple’s convention).
  117.  
  118. Both front ends use the same general-purpose subroutine: LoadClut(), which in
  119. turn calls the hardware-specific routine appropriate to the particular video 
  120. device being used.
  121.  
  122. The useMostSignificantBits bit of the “flags” argument specifies whether to use 
  123. Apple’s convention (for users of SetEntriesQuickly) or Raynald’s convention 
  124. (for users of macltset).
  125.  
  126. At the moment all the supported video cards have 8-bit DACs, except the RasterOps
  127. ProColor 32, which has 9-bit DACs. If the useMostSignificantBits flag is true
  128. then you don’t need to worry, as the least significant bit of the 9-bit DAC
  129. simply picks up the next lower bit from your numbers, giving you a tad more
  130. precision. However, if useMostSignificantBits flag is false then, in order to
  131. use the full range of the DAC you must make all your numbers twice as big, or --
  132. cludge time! -- set the useOnly8Bits flag, to request that your 8-bit numbers be
  133. multiplied by two, allowing you to use the whole range of the DAC without
  134. changing the rest of your program, but wasting the DAC’s least significant bit
  135. by setting it permanently to zero.
  136.  
  137. SUSPENDING INTERRUPTS. If you wish, the low-level routines will suspend
  138. interrupts while loading the clut. Presumably Raynald had his reasons for
  139. implementing this, so this “feature” is enabled when you use macltset(). Peter
  140. Lennie writes, “The switch to uninterruptable processing during the write is, I
  141. think, out of the original drivers (though I’m not absolutely sure).  I imagine
  142. it’s to avoid display glitches that would result from some higher priority
  143. interrupt suspending a clut rewrite somewhere in the middle.” However, I (dgp)
  144. don’t see any advantage to suspending interrupts, and believe that there is a
  145. significant downside if you are trying to keep track of the VBL interrupts on
  146. several video cards, since suspending interrupts for 1 or 2 ms might be long
  147. enough to miss a whole VBL interval. Thus SetEntriesQuickly disables this
  148. “feature”. However, this is not a philosophical debate. We all agree that
  149. interrupts should be suspended if doing otherwise would occasionally result in a
  150. visible glitch. Does anyone know?
  151.  
  152. OSErr WaitForNextBlanking(GDHandle device);
  153.  
  154. Waits for beginning of next blanking interval. Currently this supports only the
  155. Toby and HiRes cards (Apple’s original video cards, now obsolete).
  156.  
  157. SPEED. SetEntriesQuickly() is self contained. You simply give it the GDHandle of
  158. your video device (as returned, e.g. by GetScreenDevice), and tell it what you
  159. want to do to the clut. In order to do this for you it needs to figure out a
  160. bunch of stuff about your video device. This research takes time; the first time
  161. you call it for a particular device it takes on the order of 1 ms to look up
  162. stuff. However, it saves this info in a cache, for each device, for quick
  163. retrieval on subsequent occasions. The implication is that programs that use
  164. SetEntriesQuickly ought to call it once just for practice (to get the cache
  165. loading over with) before using it in a situation where speed matters.
  166.  
  167. The coding of the LoadClut “driver” routines is a compromise between the needs
  168. of SetEntriesQuickly and macltset, which both use them. I decided not to write
  169. separate clut loading loops for the two cases (use most- vs. least-significant
  170. bits). I believe (but have not tested) that adding a register offset instead of
  171. using an autoincrement instruction incurs essentially no time penalty because
  172. the processor automatically overlaps the execution of such instructions. So I
  173. think that SetEntriesQuickly is running flat out, and don’t see any prospect of
  174. speeding it up significantly. On the other hand, I suspect that fetching the
  175. least significant byte by doing a byte access to an odd address (for macltset)
  176. does slow things down perhaps 30% (though I haven’t timed it) over doing a word
  177. access to an even address, as Raynald had originally coded it. If that speed
  178. loss is unacceptable, then one could insert an if(flags&useMostSignificantBits)
  179. statement into the relevant subroutine and write two separate loops optimized
  180. for the two cases. My guess is that the current compromise will be acceptable to
  181. all users.
  182.  
  183. A NOTE ON SPEED FROM DAVID BRAINARD:
  184. We have been looking pretty closely at video timing.  In our hands,
  185. SetEntriesQuickly does not always succeed in writing the CLUT during the
  186. vertical blank interval.  In particular, with the Apple 8-24 board on a IIfx
  187. running in the 800 by 600 mode at 75 Hz, it is a little too slow.  This causes a
  188. visible glitch at the top of the screen.  Whether it is fast enough is probably
  189. very hardware-configuration dependent, but it might be worth emphasizing in the
  190. documentation that use is caveat emptor.  You give < 2 ms as the write time,
  191. which is roughly correct, but not always fast enough. I may end up writing an
  192. assembler version to see if I can push it by 25%, which is about what I need.
  193. [However, assembly code won't be compatible with the Power PC.-dgp]
  194.  
  195. IMPROVEMENTS:
  196. It is hoped that others will add to the functionality of this routine. Please
  197. share your enhancements with others by sending them to denis_pelli@isr.syr.edu
  198. for inclusion in the VideoToolbox.
  199.  
  200. Those wishing to support new video devices should begin by buying and reading
  201. Apple’s Designing Cards and Drivers, 3rd Ed., Addison-Wesley, and then use the
  202. VideoToolbox utility GetVideoDrivers to copy all your drivers into resource
  203. files, and use ResEdit with CODE editor to peruse them. The ResEdit CODE editor
  204. is a public domain file distributed by:
  205. Ira L. Ruben
  206. Apple Computer, Inc.
  207. 20525 Mariani Ave., MS: 37-A
  208. Cupertino, Ca. 95014
  209. Ira@Apple.Com
  210. ftp://ftp.apple.com/dts/mac/tools/resedit/resedit-2-1-code-editor...
  211.  
  212. By the way, assembly code is hard to write, read, and maintain,
  213. and the speed advantage is negligible, about 10%. I suggest that
  214. all new code be written in C.
  215.  
  216. It is logical that we identify the video card by the card name,
  217. GDCardName(driver), but in fact getting the card name is very slow (1.5 ms)
  218. whereas getting the driver name is fast, GDName(driver), and would be
  219. sufficiently unique for our purposes. (E.g. the Toby and TFB video cards have
  220. the same driver, and our code works for both cards.) 
  221.  
  222. KNOWN BUGS:
  223. Has not been tested on all the video devices that are supposed to be supported.
  224. Please run the demo TimeVideo, and send the results file to denis_pelli@isr.syr.edu
  225.  
  226. Does not work with the RasterOps ProColor 32. Hopefully this will be fixed soon.
  227.  
  228. The Quadra code requires that start==0. (Apparently the same problem occurs when
  229. running the 8•24 card on a Quadra 840AV.) This could probably be figured out and
  230. fixed pretty easily if someone took the time to do so.
  231.  
  232. I recommend using the standard drivers (i.e. GDSetEntries/GDDirectSetEntries)
  233. instead of SetEntriesQuickly for the Toby and High Resolution video cards and
  234. the Mac IIci built-in video. Those standard drivers work fine, whereas for those
  235. devices SetEntriesQuickly produces visible dynamic black specks as it accesses
  236. the clut.
  237.  
  238. None of these routines wait for the vertical blanking interval before loading
  239. the clut. On older video devices--Toby, HiRes, Mac IIci--this results in visible
  240. dynamic black specks on the screen. I (dgp) consider this a bug, but, for most
  241. of these devices I don’t know how to wait for the end of frame, short of setting
  242. up an interrupt. (Just about every video card has a bit that one could monitor,
  243. but its address is usually undocumented.) Newer devices seem to be ok, because of
  244. dual-ported RAMDAC memory. Check this out on your devices by running TimeVideo.
  245.  
  246. RASTEROPS 8L & 24L:
  247. Rhea Eskew, eskew@neu.edu, writes "I use a RasterOps 8L board (it's probably
  248. obsolete now), which has one of those lousy drivers. However, RasterOps was nice
  249. enough to provide me with the register address and the blanking bit address, so
  250. I write directly to the hardware. The RasterOps 8L is the same as the 24L, just
  251. less memory. So I presume the register addresses are the same for the two
  252. boards. The board's base address is Fx000000, where x=Nubus slot number. The
  253. CLUT offset is FA0000. The vertical blanking bit is at offset F70000. Wait for
  254. bits 1 and 2 to both go high, then low. Ignore bit 0.
  255.      Here is the 680x0 assembly code that I use to write directly to the hardware of
  256. my RasterOps 8L board, to fill the clut. It's based on some asm supplied by
  257. RasterOps. Because I use FORTH, the opcode conventions shown below look a bit
  258. different from conventional 680x0 opcodes, but of course they do the same
  259. things. I think they could be figured out pretty easily (and I'm available if
  260. someone wants help)."
  261. hex                         \ everything's in hex
  262. FC000000 constant Cardbase    \ my card is in slot C -- the base address is
  263.                             \ Fx000000; substitute your hex slot # for x
  264. CardBase FA0000 + constant ClutBase        \ RasterOps-supplied offset
  265. CardBASE F70000    + constant VertBitOff    \ offset to vertical blanking register
  266. \ This is a FORTH code routine -- takes as stack-input parameters the listed
  267. \ numbers with VertBitOff on top of stack.
  268. \ ClutBase is base addr of rasterops board (FCA0000 for slot C)+Clutoffset (00FA0000)
  269. \ Sourceaddr is base address in RAM of the ColorSpecs (index,red,green,blue).
  270. \ count is number'of'em. (The clut data are stored as WORDS not bytes.)
  271. \ VertBitOff is register for vertical blanking (RObase+F70000)
  272. \ 'sp' stands for stack pointer = register a7
  273. \ (This version seems to work w/o glitches -- moved blanking up to top of routine.)
  274. code    R-OSetPal ( ClutBase\Sourceaddr\count\VertBitOff -- )
  275.     1  D0 MOVEQ, A05D w,    \ swappmmumode to 32bit
  276.     a4    d3    long    move,    \ save UP (a4) in d3; restore at end!
  277.     sp )+ a4    long move,    \ put vertbitoff into a4 
  278.     \ wait for blanking
  279.     begin,
  280.         a4 ()   1D 2    d1    bfextu,    \ offset is 29=$1D, bits 2 and 1 (bit 0 not used!!!)
  281.         d1    3      byte subq,    \ 3 equals 2 bits set at low end of d1
  282.     eq        until,            \ wait until it equals 3
  283.     begin,
  284.         a4 ()   1D 2    d1    bfextu,    \ offset is 29=$1D bits 2 and 1 (bit 0 not used!!!)
  285.     eq        until,            \ wait until both bits are zero
  286.     \ blanking done
  287.     sp )+ D0 long move,        \ put count to d0
  288.     sp )+ a1 long move,        \ put source into a1
  289.     sp )+ A0    long move,    \ put destination (clutbase) to a0
  290.     begin,
  291.         a1 )+ 3 a0  i) byte move,    \ index 
  292.         a1    1           long    ADDQ,    \ increment an extra byte
  293.         a1 )+ 7 a0  i) byte move,    \ red
  294.         a1    1           long    ADDQ,    \ increment an extra byte
  295.         a1 )+ 7 a0  i) byte move,    \ green
  296.         a1    1           long    ADDQ,    \ increment an extra byte
  297.         a1 )+ 7 a0  i) byte move,    \ blue
  298.         a1    1           long    ADDQ,    \ increment an extra byte
  299.         d0 1 long subq,
  300.     eq until,       
  301.     d3    a4    long move,        \ Restore UP
  302.     0  D0 MOVEQ, A05D w,    \ SwapMMUMode back
  303.     next
  304. end-code
  305.  
  306. HISTORY:
  307. 8/24/92 Original setcardbase and macltset provided by Raynald Comtois
  308. (raco@wjh12.harvard.edu) to Denis Pelli.
  309.  
  310. 10/2/92 Bill Haake added code for the RasterOps ProColor 32, which has 9-bit
  311. DACs and 9-bit entries in the lookup table.
  312.  
  313. 10/1/92 Peter Lennie added code for Quadra internal video.  No provision for
  314. changing the start position in the table, (I couldn't find any relevant
  315. disassembly) so 'start' is ignored, and you should write the whole table.
  316.     
  317. 9/30/92 Bill Haake & Peter Lennie modified the code for the 8x24 card
  318. and the 8x24GC to make it a) work properly in 32-bit mode. b) to fix a bug
  319. (feature?) of the original drivers that prevented the cards running on a Quadra.
  320. The drivers exploit 'byte-smearing' on the 68020 and 68030 (Tech Note 282). This
  321. means that one can move a byte to the lowest byte address of the data register
  322. on the card, when one actually wants to put it at address+3 (!!). The functions
  323. work for all the cards (except toby, which hasn't been tested) and on internal
  324. video in both 24 and 32 bit mode on Quadra 700/950, IIfx or ci running system
  325. 7.0.1.
  326.     
  327. 9/28/92 Peter Lennie added the function findcard.
  328.  
  329. 11/23/92 Denis Pelli (dgp) eliminated all globals because they implicitly
  330. assumed that there is only one video device. All routines now accept a GDHandle
  331. specifying which video device. Simplified the logic of GetCardBase(), minimizing
  332. the dependence on card type.
  333.  
  334. 11/25/92 dgp When USE_MSB is true, all the routines now use the most significant
  335. bits of the 16-bit elements of the user-supplied color tables. When it is false
  336. the least significant bits are used. This is mostly implemented by offseting the
  337. table pointers by one byte and only reading the desired byte. •Generalized
  338. macltset() to work with tables that have an arbitrary element spacing. This
  339. allows it to work with both with Raynald's convention of three arrays of shorts,
  340. and the Apple convention of a ColorSpec array, each element of which consists of
  341. red, green, blue, and value (which is not used). •Added alias "Toby frame buffer
  342. card" for tobycard.
  343.  
  344. 11/27/92 dgp Broke out the code for each card into separate subroutines. This
  345. allows optimal register assignment for each routine, and makes it much easier to read
  346. the THINK C disassembler output. The runtime overhead of loading and unloading
  347. the stack is negligible, and could be eliminated entirely by putting all the
  348. parameters in a structure and passing a pointer to it. •Added a flag,
  349. suspendInterrupts, to make interrupt suspension optional since it may be
  350. undesirable in some applications. (Blocking interrupts for 1 ms could cause you
  351. to miss the interrupt from a video card, especially if you are trying to keep
  352. track of interrupts on several video cards at once.)
  353.  
  354. 11/30/92 dgp Wrote TestCluts, which reads back the clut and checks all
  355. values, and used it to test SetEntriesQuickly() on Quadra 950 internal video,
  356. Mac IIci internal video, hirescard, "Toby frame buffer card", and 8•24 card at
  357. all depths, for both 24- and 32-bit addressing. Toby card was tested on 68020,
  358. 68030, and 68040 processors. •Wrote documentation. •Replaced compile-time constants
  359. USE_MSB and PRO_8BITS by runtime flags passed as arguments. •Added WaitForNextBlanking()
  360. based on code from VideoTFB.c.
  361.  
  362. 12/3/92 dgp Incorporated Peter Lennie's corrections and additions to the comments above.
  363.  
  364. 12/8/92 dgp Added missing "case" to switch in WaitForNextBlanking.
  365.  
  366. 12/13/92 dgp Changed erroneous "&d" to "%d" in a printf. Added some comments to
  367. the documentation above.
  368.             
  369. 12/15/92 dgp Now get mode from device record and leave it in standard form, 
  370. i.e. with the 0x80 bit set, and only strip off that bit when actually necessary,
  371. e.g. in LoadClutMacIIci. 
  372.  
  373. 12/30/92 dgp Make sure routines return zero when there's no error.
  374.  
  375. 2/15/93    dgp Rewrote nonworking LoadClutToby in C, and made it work. Rewrote
  376. nonworking LoadClutx824 in C, and made it work. Fixed sixteenBitMode in
  377. LoadClutQuadra. Use new SwapPriority instead of Get/SetPriority.
  378.  
  379. 2/20/93    dgp    Translated LoadClutGCx824 to C. (It was ignoring the start value.)
  380.  
  381. 3/4/93    dgp    Added macIIsi to list of supported cards, since it uses the same
  382. driver as the Mac IIci. Changed definitions of string types slightly to allow
  383. compilation of this file as a code resource. However, the assembly code
  384. uses more registers than are available to a code resource.
  385.  
  386. 4/13/93    dgp    Removed 68020 requirement by translating an indexed add in LoadMacIIci to
  387. C.
  388.  
  389. 4/17/93 dgp Added support in GetCardBase for old Mac II computers whose ROM's only 
  390. support 24-bit NuBus addressing. 
  391.  
  392. 5/18/93 SetEntriesQuickly now respects the setting of the device's gray/color mode, 
  393. and maps to gray if in the device is in gray mode and pixelSize<=8. Changed prototype
  394. of macltset to specify the red, green, and blue arrays as "unsigned short" instead of 
  395. "short".
  396.  
  397. 7/7/93    dgp    Disabled some global optimizations because THINK C 6 will
  398. crash while compiling if the Radius PowerView is present: "!gopt_induction,!gopt_loop".
  399.  
  400. 7/9/93    dgp check for 32-bit addressing capability.
  401.  
  402. 6/14/94    dgp    can32 is now computed by calling TrapAvailable(_SwapMMUMode), which 
  403. returns correct answer even on Macs with dirty ROMs.
  404.  
  405. 6/14/94    dgp    Added call to SwapMMUMode in LoadClutToby, because it seemed odd not to.
  406. LoadClutMacIIci still doesn't, because the video buffer is in memory.
  407.  
  408. 6/30/94 dgp Updated the documentation.
  409.  
  410. 7/27/94 dgp Moved the list of compatible devices from the "Video synch" document
  411. to here, at the top of the file.
  412.  
  413. 7/29/94 dgp Made use of the asm directive conditional on THINK_C, for compatibility
  414. with other compilers. Changed LoadClutx824GC() to use its C instead of its asm code. 
  415. However, I don't know if the C code has been tested. GetCardType() returns nonzero
  416. only if the card is supported by the compiled code (i.e. ProColor, Quadra, and Mac
  417. IIci and IIsi are recognized only if this file is compiled by THINK C.)
  418.  
  419. 1/13/95 dgp Added information, above, from Rhea Eskew about the RasterOps 8L.
  420. */
  421. #include "VideoToolbox.h"
  422. #include <assert.h>
  423. #define _SwapMMUMode 0xA05D
  424. #define USE_ONLY_8_BITS_IN_MACLTSET 0    // 1 to use RasterOps ProColor32 as an 8-bit DAC.
  425. #if (THINK_C || THINK_CPLUS)
  426.     #pragma options(assign_registers,honor_register,redundant_loads,defer_adjust)
  427.     #pragma options(global_optimizer,!gopt_induction,!gopt_loop,gopt_cse,gopt_coloring)
  428. #endif
  429.  
  430. // These are the five user-callable routines:
  431. OSErr WaitForNextBlanking(GDHandle device);
  432. OSErr SetEntriesQuickly(GDHandle device,short start,short count,ColorSpec *table);
  433. short macltset(GDHandle device,short start
  434.     ,unsigned short* red,unsigned short* green,unsigned short* blue,short count1);
  435. short GetCardType(GDHandle device);
  436. char *GetCardBase(GDHandle device);
  437.  
  438. /*
  439. I suggest keeping the following information private to this file. In principle
  440. you could publish these card types and use them in your programs. However, in
  441. practice, I cannot see any point in doing so. If you need to identify the card
  442. name I suggest you simply use the string returned by GDCardName(device) in
  443. GDVideo.c of the VideoToolbox. (Don't forget to call DisposPtr() when you're
  444. through with the string.) Or use GDName(device), which returns the name of the
  445. card's driver, and is much quicker. If you simply want to know whether your
  446. video card is supported by SetEntriesQuickly.c then you can simply make sure
  447. that GetCardType() returns a nonzero cardType.
  448. */
  449. struct vtype {        /* associates card name and id */
  450.     char name[40];
  451.     short id;
  452. };
  453. enum {                /* card identifiers */
  454.     tobycard = 1,
  455.     hirescard,
  456.     macIIci,
  457.     macIIsi,
  458.     x824card,
  459.     x824GCcard,
  460.     quadra700,
  461.     quadra900,
  462.     quadra950,
  463.     procolor32
  464. };
  465. static struct vtype card[] = {    // card name & id        // Original author:
  466.     {"Toby frame buffer card",                tobycard},    // Raynald Comtois
  467.     {"Display_Video_Apple_TFB",                tobycard},    //     "      "
  468.     {"Mac II High-Resolution Video Card",    hirescard},    // Raynald Comtois
  469.     {"Macintosh Display Card",                x824card},    // Raynald Comtois
  470.     {"Macintosh Display Card 8•24 GC",        x824GCcard},// Raynald Comtois
  471.     #if THINK_C    // the asm directive is supported only by THINK C
  472.         {"Macintosh II Built-In Video",            macIIci},    // Raynald Comtois
  473.         {"Macintosh A Built-In Video",            macIIsi},    //     "      "
  474.         {"Macintosh E Built-In Video",            quadra700},    // Peter Lennie
  475.         {"Macintosh C Built-In Video",            quadra900},    //     "      "
  476.         {"Macintosh G Built-In Video",            quadra950},    //     "      "
  477.         {"ProColor 32",                            procolor32}    // Bill Haake
  478.     #endif
  479. };
  480. static char driverName[][40]=        // Not used at present.
  481. {
  482.     "\p.Display_Video_Apple_TFB"    // Apple “Toby frame buffer card”
  483.     ,"\p.Display_Video_Apple_HRVC"    // Apple “Mac II High-Resolution Video Card”
  484.     ,"\p.Display_Video_Apple_MDC"    // Apple 8•24 “Macintosh Display Card”
  485.     ,"\p.Display_Video_Apple_MDCGC"    // Apple 8•24GC
  486.     ,"\p.Display_Video_Apple_RBV1"    // Mac IIci and IIsi built-in video
  487.     ,"\p.Display_Video_Apple_DAFB"    // Quadra 700, 900, 950 built-in video
  488.     ,"\p.RasterOps 1.0 32XL Video Driver"    // Radius ProColor 32
  489. };
  490. enum {                            // Flags passed to LoadClut().
  491.     suspendInterrupts=1,
  492.     useMostSignificantBits=2,
  493.     useOnly8Bits=4,
  494.     waitForNextBlanking=8
  495. };
  496. enum{quadraNonzeroStart=111};    // value returned as error.
  497.     
  498. short LoadClut(GDHandle device,short start,short count
  499.     ,unsigned short* red,unsigned short* green,unsigned short* blue,long elementSpacing,short flags);
  500. OSErr LoadClutProColor(short start,short count,char *r,char *g,char *b
  501.     ,long elementSpacing,short mode,short pixelSize,short clutSize
  502.     ,char *cardBase,short flags);
  503. OSErr LoadClutQuadra(short start,short count,char *r,char *g,char *b
  504.     ,long elementSpacing,short mode,short pixelSize,short clutSize
  505.     ,char *cardBase,short flags);
  506. OSErr LoadClutMacIIci(short start,short count,char *r,char *g,char *b
  507.     ,long elementSpacing,short mode,short pixelSize,short clutSize
  508.     ,char *cardBase,short flags);
  509. OSErr LoadClutHiRes(short start,short count,char *r,char *g,char *b
  510.     ,long elementSpacing,short mode,short pixelSize,short clutSize
  511.     ,char *cardBase,short flags);
  512. OSErr LoadClutx824(short start,short count,char *r,char *g,char *b
  513.     ,long elementSpacing,short mode,short pixelSize,short clutSize
  514.     ,char *cardBase,short flags);
  515. OSErr LoadClutx824GC(short start,short count,char *r,char *g,char *b
  516.     ,long elementSpacing,short mode,short pixelSize,short clutSize
  517.     ,char *cardBase,short flags);
  518. OSErr LoadClutToby(short start,short count,char *r,char *g,char *b
  519.     ,long elementSpacing,short mode,short pixelSize,short clutSize
  520.     ,char *cardBase,short flags);
  521. /******************************************************************************/
  522. /*
  523. The arguments start, count, and table are the same as for the Color Manager call
  524. SetEntries(), documented in Inside Macintosh V-143. (Except that a count==-1 is
  525. considered illegal here.) Apple's ideosyncratic convention is that "count" is
  526. "zero-based", meaning that it is one less than the number of clut entries that
  527. you want to modify. "count" must be at least zero. Returns zero if successful,
  528. nonzero if unsuccessful, i.e. illegal arguments.
  529. */
  530. OSErr SetEntriesQuickly(GDHandle device,short start,short count,ColorSpec *table)
  531. {
  532.     short flags=useMostSignificantBits;
  533.     //flags+=suspendInterrupts;        // Optional, no
  534.     //flags+=waitForNextBlanking;    // Optional, no
  535.  
  536.     return LoadClut(device,start,count
  537.         ,&table[0].rgb.red,&table[0].rgb.green
  538.         ,&table[0].rgb.blue,sizeof(table[0]),flags);
  539. }
  540. /******************************************************************************/
  541. short macltset(GDHandle device,register short start
  542.     ,unsigned short* red,unsigned short* green,unsigned short* blue,short count1)
  543. {
  544.     short flags=0;
  545.     flags+=suspendInterrupts;        // Optional
  546.     #if USE_ONLY_8_BITS_IN_MACLTSET
  547.         flags+=useOnly8Bits;        // Optional
  548.     #endif
  549.     //flags+=waitForNextBlanking;    // Optional
  550.     
  551.     return LoadClut(device,start,count1-1,red,green,blue,sizeof(red[0]),flags);
  552. }
  553. /******************************************************************************/
  554. /*
  555. The first call to GetCardType for a particular device takes 1.5-3 ms, depending
  556. on your computer's speed, because it takes Apple's Slot Manager a long time to
  557. get the card name. However, GetCardType's answers are cached so subsequent calls
  558. for a previously queried device will be fast <100 µs.
  559. */
  560. short GetCardType(GDHandle device)    // returns card type, if known, or zero if not.
  561. {
  562.     register short i;
  563.     short cardType;
  564.     char *name;
  565.     static GDHandle deviceCache[MAX_SCREENS];
  566.     static short typeCache[MAX_SCREENS];
  567.     
  568.     // Do we already know the answer? Check the cache.
  569.     for(i=0;i<MAX_SCREENS;i++)if(device==deviceCache[i])return typeCache[i];
  570.     // Get card name, see if it's in our list of known cards
  571.     name=GDCardName(device);
  572.     cardType=0;
  573.     for (i=0; i<sizeof(card)/sizeof(card[0]); i++){
  574.         if(strcmp(name,card[i].name)==0){
  575.             cardType=card[i].id;
  576.             break;
  577.         }
  578.     }
  579.     DisposePtr(name);
  580.     // Save answer in cache.
  581.     for(i=0;i<MAX_SCREENS;i++)if(deviceCache[i]==0){
  582.         typeCache[i]=cardType;
  583.         deviceCache[i]=device;
  584.         break;
  585.     }
  586.     return cardType;
  587. }
  588. /******************************************************************************/
  589. long internalVideoBase:0xDD8;    // Undocumented System global
  590.  
  591. char *GetCardBase(GDHandle device)
  592. {
  593.     long cardBase,slot;    /* slot must be declared long */
  594.     short cardType;
  595.     
  596.     slot=GetDeviceSlot(device);
  597.     if(slot==0){
  598.         // Built-in video, not in a NuBus slot.
  599.         // E.g.: macIIci,macIIsi,quadra700,quadra900,quadra950
  600.         #if 1
  601.             // This C is equivalent to Raynald's assembly code below.
  602.             cardBase = *(long *)(internalVideoBase + *(long *)internalVideoBase + 56);
  603.         #else
  604.             asm {
  605.                 move.l 0xDD8,a0        /* get card base address */
  606.                 adda.l (a0),a0
  607.                 move.l 56(a0),a1
  608.                 move.l a1,cardBase
  609.             }
  610.         #endif
  611.     }else{
  612.         // Video card in NuBus slot
  613.         cardType=GetCardType(device);
  614.         switch(cardType){
  615.             case x824GCcard:
  616.                 cardBase = slot<<28;    // a superslot
  617.                 break;
  618.             case tobycard:
  619.             case hirescard:
  620.                 cardBase = (slot<<24) | 0xF0000000;
  621.                 cardBase+= (slot<<20);    // Support old Mac II 24-bit NuBus addressing
  622.                 break;
  623.             case procolor32:             // RasterOps
  624.             case x824card:
  625.             default:
  626.                 cardBase = (slot<<24) | 0xF0000000;
  627.                 break;
  628.         }
  629.     }
  630.     return (char *)cardBase;
  631. }
  632. /******************************************************************************/
  633. short LoadClut(GDHandle device,short start,short count
  634.     ,unsigned short* red,unsigned short* green,unsigned short* blue
  635.     ,long elementSpacing,short flags)
  636. {
  637.     char *cardBase;
  638.     short cardType=0,pixelSize,mode;
  639.     short clutSize;     // entries in the lookup table
  640.     int error,i,j;
  641.     short isGray;
  642.     unsigned short grayTable[256];
  643.     
  644.     if(device==NULL)return 1;
  645.     cardType=GetCardType(device);    // takes 1.7 ms the first time for each device.
  646.     if(cardType==0)return 1;
  647.     cardBase=GetCardBase(device);
  648.     clutSize=GDClutSize(device);
  649.     pixelSize=(**(**device).gdPMap).pixelSize;
  650.     mode=(**device).gdMode;
  651.     
  652.     // Check range.
  653.     if(start>clutSize-1 || start<0 || count+start>clutSize-1 || count<0)return 1;
  654.     
  655.     // We're going to use these RAM addresses in 32-bit mode.
  656.     red = (unsigned short *)StripAddress(red);
  657.     green = (unsigned short *)StripAddress(green);
  658.     blue = (unsigned short *)StripAddress(blue);
  659.  
  660.     if(waitForNextBlanking & flags){
  661.         WaitForNextBlanking(device);
  662.     }
  663.     
  664.     isGray=!TestDeviceAttribute(device,gdDevType);
  665.     if(isGray && pixelSize<=8){
  666.         j=elementSpacing/sizeof(*red);
  667.         for(i=0;i<=count;i++){
  668.             grayTable[i]=*red*0.30+*green*0.59+*blue*0.11;
  669.             red+=j;
  670.             green+=j;
  671.             blue+=j;
  672.         }
  673.         elementSpacing=sizeof(grayTable[0]);
  674.         red=green=blue=grayTable;
  675.     }
  676.     
  677.     // After the above setting up, actually loading 256x3 clut entries takes <2 ms.
  678.     switch (cardType) {
  679.         // I packaged the code for each case into a separate subroutine
  680.         // in order to allow the THINK C compiler to optimize each
  681.         // one independently. An important consideration is that the THINK C 5.04
  682.         // compiler disables most optimizations for any function that includes
  683.         // the "asm" directive anywhere within the function. Thus mixing C and assembly
  684.         // will result in inefficient C. No less important, the THINK C Disassemble
  685.         // command is very handy in writing fast C code, but produces an uncommented 
  686.         // listing, which is much easier to read if the separate routines are each 
  687.         // named subroutines.
  688.         case procolor32:
  689.             error=LoadClutProColor(start,count,(char *)red,(char *)green,(char *)blue,
  690.                 elementSpacing,mode,pixelSize,clutSize,cardBase,flags);
  691.             break;
  692.         case quadra700:
  693.         case quadra900:
  694.         case quadra950:
  695.             error=LoadClutQuadra(start,count,(char *)red,(char *)green,(char *)blue,
  696.                 elementSpacing,mode,pixelSize,clutSize,cardBase,flags);
  697.             break;
  698.         case macIIci:
  699.         case macIIsi:
  700.             error=LoadClutMacIIci(start,count,(char *)red,(char *)green,(char *)blue,
  701.                 elementSpacing,mode,pixelSize,clutSize,cardBase,flags);
  702.             break;
  703.         case hirescard:
  704.             error=LoadClutHiRes(start,count,(char *)red,(char *)green,(char *)blue,
  705.                 elementSpacing,mode,pixelSize,clutSize,cardBase,flags);
  706.             break;
  707.         case x824card:
  708.             error=LoadClutx824(start,count,(char *)red,(char *)green,(char *)blue,
  709.                 elementSpacing,mode,pixelSize,clutSize,cardBase,flags);
  710.             break;
  711.         case x824GCcard:
  712.             error=LoadClutx824GC(start,count,(char *)red,(char *)green,(char *)blue,
  713.                 elementSpacing,mode,pixelSize,clutSize,cardBase,flags);
  714.             break;
  715.         case tobycard:
  716.             error=LoadClutToby(start,count,(char *)red,(char *)green,(char *)blue,
  717.                 elementSpacing,mode,pixelSize,clutSize,cardBase,flags);
  718.             break;
  719.     }
  720.     return error;
  721. }
  722. /******************************************************************************/
  723. OSErr LoadClutProColor(short start,register short count
  724.     ,register char *red,register char *green,register char *blue
  725.     ,register long elementSpacing
  726.     ,short mode,short pixelSize,short clutSize,char *cardBase,short flags)
  727. {
  728. #if THINK_C
  729.     char mmuMode=true32b,priority=7;
  730.     register long bitShift;
  731.     static Boolean can32,firstTime=1;
  732.  
  733.     if(firstTime){
  734.         can32=TrapAvailable(_SwapMMUMode);
  735.         firstTime=0;
  736.     }
  737.     if(useMostSignificantBits & flags){
  738.         bitShift=9;
  739.     }else{
  740.         if(useOnly8Bits & flags) bitShift=1;
  741.         else bitShift=0;
  742.     }
  743.     if(suspendInterrupts & flags)SwapPriority(&priority);
  744.     if(can32)SwapMMUMode(&mmuMode);
  745.     asm {
  746.         move.l cardBase,a1        /* get card base address */
  747.         adda.l    #0xf60000,a1    /* offset to control registers */        
  748.     @9    move.w    start,2(a1)        /* Set the index on the card */
  749.         move.w (red),d1
  750.         add.l elementSpacing,red
  751.         lsl.w bitShift,d1
  752.         move.w d1,14(a1)
  753.         move.w (green),d1
  754.         add.l elementSpacing,green
  755.         lsl.w bitShift,d1
  756.         move.w d1,14(a1)
  757.         move.w (blue),d1
  758.         add.l elementSpacing,blue
  759.         lsl.w bitShift,d1
  760.         move.w d1,14(a1)
  761.         addq.w    #1,start        /* Point to next entry in table */
  762.         dbf count,@9
  763.     }
  764.     if(can32)SwapMMUMode(&mmuMode);
  765.     if(suspendInterrupts & flags)SwapPriority(&priority);
  766.     return 0;
  767. #else
  768.     start;count;red;green;blue;elementSpacing;mode;pixelSize;clutSize;cardBase;flags;    // prevent "unused argument" warning
  769.     return 1;
  770. #endif
  771. }
  772. OSErr LoadClutQuadra(short start,register short count
  773.     ,register char *red,register char *green,register char *blue
  774.     ,register long elementSpacing
  775.     ,short mode,short pixelSize,short clutSize,char *cardBase,short flags)
  776. {
  777. #if THINK_C
  778.     char mmuMode=true32b,priority=7;
  779.     static Boolean can32,firstTime=1;
  780.  
  781.     if(firstTime){
  782.         can32=TrapAvailable(_SwapMMUMode);
  783.         firstTime=0;
  784.     }
  785.     if(start!=0){
  786.         //printf("LoadClutQuadra: start must be zero\n");
  787.         return quadraNonzeroStart;
  788.     }
  789.     if(!(useMostSignificantBits & flags)){
  790.         // Point to less significant byte of word.
  791.         red++;
  792.         green++;
  793.         blue++;
  794.     }
  795.     if(suspendInterrupts & flags)SwapPriority(&priority);
  796.     if(can32)SwapMMUMode(&mmuMode);
  797.     if(mode!=sixteenBitMode)asm{
  798.         move.l cardBase,a1
  799.         lea 0x210(a1), a1
  800.         clr.l -16(a1)
  801.     @4    move.b (red),d1
  802.         add.l elementSpacing,red
  803.         move.l d1,(a1)
  804.         move.b (green),d1
  805.         add.l elementSpacing,green
  806.         move.l d1,(a1)
  807.         move.b (blue),d1
  808.         add.l elementSpacing,blue
  809.         move.l d1,(a1)
  810.         dbf count,@4
  811.     }else asm{
  812.     // In sixteenBitMode the clut addressing is weird.
  813.     // I arrived at the following solution by trial and error.
  814.     // It's a kludge, but is still fast enough. dgp.
  815.         move.l cardBase,a1
  816.         lea 0x210(a1), a1
  817.         clr.l -16(a1)
  818.     @44    move.b (red),d1
  819.         move.l d1,(a1)
  820.         move.b (green),d1
  821.         move.l d1,(a1)
  822.         move.b (blue),d1
  823.         move.l d1,(a1)
  824.  
  825.         move.b (red),d1
  826.         move.l d1,(a1)
  827.         move.b (green),d1
  828.         move.l d1,(a1)
  829.         move.b (blue),d1
  830.         move.l d1,(a1)
  831.  
  832.         move.b (red),d1
  833.         move.l d1,(a1)
  834.         move.b (green),d1
  835.         move.l d1,(a1)
  836.         move.b (blue),d1
  837.         move.l d1,(a1)
  838.  
  839.         move.b (red),d1
  840.         move.l d1,(a1)
  841.         move.b (green),d1
  842.         move.l d1,(a1)
  843.         move.b (blue),d1
  844.         move.l d1,(a1)
  845.  
  846.         move.b (red),d1
  847.         move.l d1,(a1)
  848.         move.b (green),d1
  849.         move.l d1,(a1)
  850.         move.b (blue),d1
  851.         move.l d1,(a1)
  852.  
  853.         move.b (red),d1
  854.         move.l d1,(a1)
  855.         move.b (green),d1
  856.         move.l d1,(a1)
  857.         move.b (blue),d1
  858.         move.l d1,(a1)
  859.  
  860.         move.b (red),d1
  861.         move.l d1,(a1)
  862.         move.b (green),d1
  863.         move.l d1,(a1)
  864.         move.b (blue),d1
  865.         move.l d1,(a1)
  866.  
  867.         move.b (red),d1
  868.         add.l elementSpacing,red
  869.         move.l d1,(a1)
  870.         move.b (green),d1
  871.         add.l elementSpacing,green
  872.         move.l d1,(a1)
  873.         move.b (blue),d1
  874.         add.l elementSpacing,blue
  875.         move.l d1,(a1)
  876.  
  877.         dbf count,@44
  878.     }
  879.     if(can32)SwapMMUMode(&mmuMode);
  880.     if(suspendInterrupts & flags)SwapPriority(&priority);
  881.     return 0;
  882. #else
  883.     start;count;red;green;blue;elementSpacing;mode;pixelSize;clutSize;cardBase;flags;    // prevent "unused argument" warning
  884.     return 1;
  885. #endif
  886. }
  887. OSErr LoadClutMacIIci(register short start,register short count
  888.     ,register char *red,register char *green,register char *blue
  889.     ,register long elementSpacing
  890.     ,short mode,short pixelSize,short clutSize,char *cardBase,short flags)
  891. {
  892. #if THINK_C
  893.     static char realstartindex[] = {0xFE, 0xFC, 0xF0, 0x00,0,0,0};
  894.     char priority=7;
  895.     static Boolean can32,firstTime=1;
  896.  
  897.     if(firstTime){
  898.         can32=TrapAvailable(_SwapMMUMode);
  899.         firstTime=0;
  900.     }
  901.     if(!(useMostSignificantBits & flags)){
  902.         // Point to less significant byte of word.
  903.         red++;
  904.         green++;
  905.         blue++;
  906.     }
  907.     if(suspendInterrupts & flags)SwapPriority(&priority);
  908.     mode&=7;
  909.     start+=realstartindex[mode];
  910.     asm {
  911.         move.w mode,d1
  912.         move.l cardBase,a0        // get card base address
  913.         move.l a0,a1
  914. //        move.b #255,8(a0)        // not necessary
  915.         move.b start,(a0)
  916.         addq.l #4,a1
  917.     @3    move.b (red),d1
  918.         add.l elementSpacing,red
  919.         move.b d1,(a1)
  920.         move.b (green),d1
  921.         add.l elementSpacing,green
  922.         move.b d1,(a1)
  923.         move.b (blue),d1
  924.         add.l elementSpacing,blue
  925.         move.b d1,(a1)
  926.         dbf count,@3
  927.     }
  928.     if(suspendInterrupts & flags)SwapPriority(&priority);
  929.     return 0;
  930. #else
  931.     start;count;red;green;blue;elementSpacing;mode;pixelSize;clutSize;cardBase;flags;    // prevent "unused argument" warning
  932.     return 1;
  933. #endif
  934. }
  935. // High resolution video card
  936. //#define HRVCBase            0x80000
  937. #define HRVCClutAddrReg        0x940E0
  938. #define HRVCClutWDataReg    0x940E4
  939. //#define HRVCClutRDataReg    0x94054
  940. OSErr LoadClutHiRes(short start,register short count
  941.     ,register char *red,register char *green,register char *blue
  942.     ,register long elementSpacing
  943.     ,short mode,short pixelSize,short clutSize,char *cardBase,short flags)
  944. {
  945.     char *bytePtr;
  946.     char mmuMode=true32b,priority=7;
  947.     static Boolean can32,firstTime=1;
  948.  
  949.     mode;pixelSize;    // prevent "unused argument" warning
  950.     if(firstTime){
  951.         can32=TrapAvailable(_SwapMMUMode);
  952.         firstTime=0;
  953.     }
  954.     if(!(useMostSignificantBits & flags)){
  955.         // Point to less significant byte of word.
  956.         red++;
  957.         green++;
  958.         blue++;
  959.     }
  960.     if(suspendInterrupts & flags)SwapPriority(&priority);
  961.     if(can32)SwapMMUMode(&mmuMode);
  962.     red+=count*elementSpacing;
  963.     green+=count*elementSpacing;
  964.     blue+=count*elementSpacing;
  965.     // We'll start with clut entry start+count, and work
  966.     // down from there to clut entry start. The clut address
  967.     // register counts down automatically.
  968.     *(cardBase+HRVCClutAddrReg)=~(clutSize-1-start-count);
  969.     bytePtr=cardBase+HRVCClutWDataReg;
  970.     // This is the key loop. 
  971.     // This C code is only about 10% slower than the original assembly code.
  972.     elementSpacing= -elementSpacing;
  973.     do{
  974.         *bytePtr=~ *red;
  975.         red+=elementSpacing;
  976.         *bytePtr=~ *green;
  977.         green+=elementSpacing;
  978.         *bytePtr=~ *blue;
  979.         blue+=elementSpacing;
  980.     }while(--count>=0);
  981.     if(can32)SwapMMUMode(&mmuMode);
  982.     if(suspendInterrupts & flags)SwapPriority(&priority);
  983.     return 0;
  984. }
  985. // Macintosh display card (8•24)
  986. //#define MDCVideoBase        0xA00
  987. #define MDCClutAddrReg        0x200200
  988. #define MDCClutDataReg        0x200204
  989. OSErr LoadClutx824(short start,register short count
  990.     ,register char *red,register char *green,register char *blue
  991.     ,register long elementSpacing
  992.     ,short mode,short pixelSize,short clutSize,char *cardBase,short flags)
  993. {
  994.     char mmuMode=true32b,priority=7;
  995.     register char *clut;
  996.     char *clutIndex;
  997.     static Boolean can32,firstTime=1;
  998.  
  999.     mode;pixelSize;clutSize;    // prevent "unused argument" warning
  1000.     if(firstTime){
  1001.         can32=TrapAvailable(_SwapMMUMode);
  1002.         firstTime=0;
  1003.     }
  1004.     if(!(useMostSignificantBits & flags)){
  1005.         // Point to less significant byte of word.
  1006.         red++;
  1007.         green++;
  1008.         blue++;
  1009.     }
  1010.     if(suspendInterrupts & flags)SwapPriority(&priority);
  1011.     if(can32)SwapMMUMode(&mmuMode);
  1012.     clut=cardBase+MDCClutDataReg+3;
  1013.     clutIndex=cardBase+MDCClutAddrReg;
  1014.     *clutIndex=start;
  1015.     for(;count>=0;count--){
  1016.         *clut=*red;
  1017.         red+=elementSpacing;
  1018.         *clut=*green;
  1019.         green+=elementSpacing;
  1020.         *clut=*blue;
  1021.         blue+=elementSpacing;
  1022.     }
  1023.     if(can32)SwapMMUMode(&mmuMode);
  1024.     if(suspendInterrupts & flags)SwapPriority(&priority);
  1025.     return 0;
  1026. }
  1027. // Macintosh display card 8•24 GC
  1028. #define MDCgcClutAddrReg    0x6C00000
  1029. #define MDCgcClutDataReg    0x6C00004
  1030. OSErr LoadClutx824GC(short start,register short count
  1031.     ,register char *red,register char *green,register char *blue
  1032.     ,register long elementSpacing
  1033.     ,short mode,short pixelSize,short clutSize,char *cardBase,short flags)
  1034. {
  1035.     char mmuMode=true32b,priority=7;
  1036.     register long *clut;
  1037.     char *clutIndex;
  1038.     static Boolean can32,firstTime=1;
  1039.  
  1040.     mode;pixelSize;clutSize;    // prevent "unused argument" warning
  1041.     if(firstTime){
  1042.         can32=TrapAvailable(_SwapMMUMode);
  1043.         firstTime=0;
  1044.     }
  1045.     if(!(useMostSignificantBits & flags)){
  1046.         // Point to less significant byte of word.
  1047.         red++;
  1048.         green++;
  1049.         blue++;
  1050.     }
  1051.     if(suspendInterrupts & flags)SwapPriority(&priority);
  1052.     if(can32)SwapMMUMode(&mmuMode);
  1053.     clutIndex=cardBase+MDCgcClutAddrReg;
  1054.     *clutIndex=start;
  1055.     #if 1
  1056.         clut=(long *)(cardBase+MDCgcClutDataReg);
  1057.         for(;count>=0;count--){
  1058.             *clut=(long)(*red)<<24;
  1059.             red+=elementSpacing;
  1060.             *clut=(long)(*green)<<24;
  1061.             green+=elementSpacing;
  1062.             *clut=(long)(*blue)<<24;
  1063.             blue+=elementSpacing;
  1064.         }
  1065.     #else
  1066.         asm {
  1067.             move.l cardBase,a1
  1068.             add.l #MDCgcClutDataReg,a1
  1069.         @8    move.b (red),d1
  1070.             add.l    elementSpacing,red
  1071.             ror.l    #8,d1
  1072.             move.l d1,(a1)
  1073.             move.b (green),d1
  1074.             add.l    elementSpacing,green
  1075.             ror.l    #8,d1
  1076.             move.l d1,(a1)
  1077.             move.b (blue),d1
  1078.             add.l elementSpacing,blue
  1079.             ror.l    #8,d1
  1080.             move.l d1,(a1)
  1081.             dbf count,@8
  1082.         }
  1083.     #endif
  1084.     if(can32)SwapMMUMode(&mmuMode);
  1085.     if(suspendInterrupts & flags)SwapPriority(&priority);
  1086.     return 0;
  1087. }
  1088. // Toby frame buffer
  1089. //#define    TFBBase            0x80000
  1090. //#define TFBBufMid            0x80008
  1091. //#define TFBBufLow            0x8000C
  1092. //#define    TFBIBase        0x8fffc
  1093. #define TFBClutWDataReg        0x90018
  1094. //#define TFBClutRDataReg    0x90028
  1095. #define TFBClutAddrReg        0x9001C
  1096. #define    TFBReadVSync        0xD0000
  1097. //#define    TFBReadVInt        0xD0004
  1098. //#define    TFBReadIntlc    0xD0008
  1099. //#define    TFBVIntEnable    0xA0000
  1100. //#define    TFBVIntDisable    0xA0004
  1101. OSErr LoadClutToby(short start,register short count
  1102.     ,register char *red,register char *green,register char *blue
  1103.     ,register long elementSpacing
  1104.     ,short mode,short pixelSize,short clutSize,char *cardBase,short flags)
  1105. {
  1106.     register long index;
  1107.     char mmuMode=true32b,priority=7;
  1108.     register char *clut,*clutIndex;
  1109.     short shift;
  1110.     static Boolean can32,firstTime=1;
  1111.  
  1112.     mode;clutSize;    // prevent "unused argument" warning
  1113.     if(firstTime){
  1114.         can32=TrapAvailable(_SwapMMUMode);
  1115.         firstTime=0;
  1116.     }
  1117.     if(!(useMostSignificantBits & flags)){
  1118.         // Point to less significant byte of word.
  1119.         red++;
  1120.         green++;
  1121.         blue++;
  1122.     }
  1123.     index=(count+1)*elementSpacing;
  1124.     red+=index;
  1125.     green+=index;
  1126.     blue+=index;
  1127.     shift=8-pixelSize;
  1128.     index=start+count+1;
  1129.     clut=cardBase+TFBClutWDataReg;
  1130.     clutIndex=cardBase+TFBClutAddrReg;
  1131.     if(suspendInterrupts & flags)SwapPriority(&priority);
  1132.     if(can32)SwapMMUMode(&mmuMode);
  1133.     for(;count>=0;count--,index--){
  1134.         *clutIndex=(index<<shift)-1;
  1135.         red-=elementSpacing;
  1136.         *clut=~*red;
  1137.         green-=elementSpacing;
  1138.         *clut=~*green;
  1139.         blue-=elementSpacing;
  1140.         *clut=~*blue;
  1141.     }
  1142.     if(can32)SwapMMUMode(&mmuMode);
  1143.     if(suspendInterrupts & flags)SwapPriority(&priority);
  1144.     return 0;
  1145. }
  1146.  
  1147. OSErr WaitForNextBlanking(GDHandle device)
  1148. // WaitForNextBlanking waits for the beginning of the next vertical blanking interval.
  1149. // Returns 0 if successful, or 1 if device is not supported.
  1150. {
  1151.     register long *blankingPtr;
  1152.  
  1153.     switch(GetCardType(device)){
  1154.     case tobycard:
  1155.         blankingPtr = (long *) ((char *)GetCardBase(device) + TFBReadVSync);
  1156.         while (*blankingPtr & 1L) ;    // if we're already blanking, wait till end.
  1157.         while (!(*blankingPtr & 1L)) ; // wait until beginning of blanking interval.
  1158.         return 0;
  1159.     default:
  1160.         return 1;
  1161.     }
  1162. }
  1163.